#include "Login.h"
#include "../Game.h"

Login::Login()
{
	//ctor
	m_Server_lst.clear();
	m_Client_lst.clear();
}

Login::~Login()
{
	//dtor
	m_Server_lst.clear();
	m_Client_lst.clear();
}

// 账户验证
// return
// 		0:成功
// 		1:帐号密码错误
//  	2:没有该帐号
int Login::Verification(string _user, string _pwd, int& _userId)
{
	// 内存中验证
	int ret = Game::GetInstance().m_AccountMgr.Verification(_user, _pwd, _userId);
	if(ret == 0)
		return 0;

	if(ret == 1)
		return 1;

	// 在数据库中验证
	tUser* pUser = Game::GetInstance().m_GameDb.SelectUser(_user);
	if(pUser == nullptr)
	{
		return 2;
	}

	// 记录到内存中
	Game::GetInstance().m_AccountMgr.Cache(*pUser);
	if(pUser->pwd != _pwd)
		return 1;

	_userId = pUser->id;
	return 0;
}

void Login::AddServerInfo(Client* _pClient)
{
	if(_pClient == nullptr)
	{
		return;
	}

	ServerInfo Info;
	Info.m_fd = _pClient->m_fd;
	Info.m_ip = _pClient->m_ip;
	Info.m_name = _pClient->m_name;
	Info.m_port = _pClient->m_port;

	m_Server_lst.push_back(Info);
}


void Login::AddClientInfo(Client* _pClient)
{
	if(_pClient == nullptr)
	{
		return;
	}

	ClientInfo Info;
	Info.m_fd = _pClient->m_fd;
	Info.m_ip = _pClient->m_ip;
	Info.m_port = _pClient->m_port;

	m_Client_lst.push_back(Info);
}

// Fuction	: 获取某个服务器信息
ServerInfo* Login::GetServerInfo(int _fd)
{
	for(list<ServerInfo>::iterator iter = m_Server_lst.begin();iter != m_Server_lst.end(); iter++)
	{
		if(iter->m_fd == _fd)
		{
			return &(*iter);
		}
	}

	Debug::Error("Not found ServerInfo, _fd:", _fd);
	return nullptr;
}

// Fuction	: 获取某个客户端信息
ClientInfo* Login::GetClientInfo(int _fd)
{
	for(list<ClientInfo>::iterator iter = m_Client_lst.begin();iter != m_Client_lst.end(); iter++)
	{
		if(iter->m_fd == _fd)
		{
			return &(*iter);
		}
	}

	Debug::Error("Not found ClientInfo, _fd:", _fd);
	return nullptr;
}

int Login::GetServerCount()
{
	return m_Server_lst.size();
}

int Login::GetClientCount()
{
	return m_Client_lst.size();
}

list<ServerInfo>& Login::GetServerList()
{
	return m_Server_lst;
}

// 账户注册
// return
// 		0:成功
// 		1:帐号重复
// 		2:注册失败
int Login::Register(string _user, string _pwd)
{

	// 内存中是否已存在
	if(Game::GetInstance().m_AccountMgr.isRigster(_user))
		return 1;

	// 在数据库中中是否已存在
	if(Game::GetInstance().m_GameDb.IsFindUser(_user))
	{
		return 1;
	}

	// 插入数据库
	int newId = Game::GetInstance().m_GlobalMgr.GetValue(eGlobalKey::RegisterCount) + 1;
	tUser User1;
	User1.id = newId;
	User1.user = _user;
	User1.pwd = _pwd;
	if( Game::GetInstance().m_GameDb.InsertUser(User1) == -1)
	{
		return 2;
	}

	Game::GetInstance().m_GlobalMgr.UpdateValue(eGlobalKey::RegisterCount, newId);

	// 记录到内存中
	Game::GetInstance().m_AccountMgr.Cache(User1);

	return 0;
}
